/***************************************************************
 *
 * Filename：MainWindow.cpp
 * Abstract：the design of main window
 * version ：1.0
 * 
 * Copyright (c) 2011 SCUT DT&P FY&XC
 * 
***************************************************************/

#include <stdlib.h>
#include "MainWindow.h"
#include <QHostInfo>
#include <QDebug>

//初始化登录窗口
MainWindow::MainWindow()
{
	initWindow();
	usercount = 0;
	initUp();
  	connect(service, SIGNAL(addUser(MessagePRO *)) , this, SLOT(addUserList(MessagePRO *)));

        connect(service, SIGNAL(msgBrExit(MessagePRO *)) , this, SLOT(delUserList(MessagePRO *)));
        connect(service, SIGNAL(chgphoto(MessagePRO *)) , this, SLOT(chgUserphoto(MessagePRO *)));
}

//初始化聊天室界面和程序基本信息
void MainWindow::initWindow()
{   
	//width and height	
	resize(290,550);

        setWindowTitle(tr("QLan"));
	messageWindow = new QWidget(this);
	messageWindow->resize(200,600);
   	//messageWindow->setMinimumSize(200,600);
	//messageWindow->setMaximumSize(200,600);
	
	//显示头像
	ImageButton = new QToolButton();
        userPhoto = "./image/default.png";
        QPixmap icon(userPhoto);
 	ImageButton->setIcon(icon);
	//ImageButton->setIconSize(40,40);
	ImageButton->setIconSize(icon.size());
 	//显示用户名
	HostNameLabel = new QLabel();
	
	//显示时间？？？
	TimeLabel = new QLabel();
        TimeLabel->setText("Welcome!!");
	
	//"关于"按钮
	aboutButton = new QPushButton(tr("&About"),messageWindow);
	connect(aboutButton, SIGNAL(clicked()), this, SLOT(about()));

	//"刷新"按钮
	refurbishButton = new QPushButton(tr("&Rrfurbish"),messageWindow);
	connect(refurbishButton, SIGNAL(clicked()), this, SLOT(refurbish()));

	//用户昵称表
	userListWidget = new QListWidget(messageWindow);
	showuserlist();
	userListWidget->setMinimumSize(190,430);
	//userListWidget->setMaximumSize(200,600);
	connect(userListWidget, SIGNAL(itemDoubleClicked (QListWidgetItem*)),this,SLOT(addSub(QListWidgetItem *)));//


	//退出按钮
	quitButton = new QPushButton(tr("&Quit"),messageWindow);
	connect(quitButton,SIGNAL(clicked()), this, SLOT(close()));
			
	//布局
	QHBoxLayout *buttonLayout = new QHBoxLayout;
	buttonLayout->addWidget(aboutButton);
	buttonLayout->addWidget(refurbishButton);
        buttonLayout->addWidget(quitButton);

        QHBoxLayout *topLayout = new QHBoxLayout;
        topLayout->setMargin(10);
	topLayout->setAlignment(Qt::AlignHCenter);
	topLayout->addWidget(ImageButton);
	topLayout->addWidget(HostNameLabel);
	topLayout->addWidget(TimeLabel);

	QGridLayout *mainLayout = new QGridLayout;
	mainLayout->addLayout(topLayout,0,0);
	mainLayout->addWidget(userListWidget,1,0);
	mainLayout->addLayout(buttonLayout,2,0,1,2);
	mainLayout->setSizeConstraint(QLayout::SetFixedSize);
	
	messageWindow->setLayout(mainLayout);
	getHostInformation();
        connect(ImageButton,SIGNAL(clicked()),this,SLOT(slotOpenImageDlg()));
	messageWindow->show();
}

//初始化服务器
void MainWindow::initUp()
{
    qDebug()<<"SEVER AND TCPSERVER in MainWindow::initUP";
    service = new Serve;
}

//退出，未完成
void MainWindow::exit()
{

}

//根据sublist显示用户到列表
void MainWindow::showuserlist()
{
	userListWidget->clear();
        qDebug()<<"UserCount:"<<usercount<<"in MainWindow::showuserlist";

	foreach(QString str, sublist)
	{
		qDebug()<<"User:"<<str;
                qDebug()<<userphoto[str];
                userListWidgetItem = new QListWidgetItem(QIcon(userphoto[str]), str, userListWidget);
	}
}

//添加用户到sublist
void MainWindow::addUserList(MessagePRO *msg)
{	
	qDebug()<<"AddUserList:"<<msg->address<<":"<<msg->username;
	QString str;
        //QString strphoto;
	if (msg->hostname == msg->username+"*")
		str=msg->address.toString()+":"+msg->username+"*";
                //strphoto = ""
	else
		str=msg->address.toString()+":"+msg->username;
	qDebug()<<"AddUserList: msg->command:"<<msg->command;
	qDebug()<<"subislist[str1]:" << subislist[str];
        unsigned long sendM;
        sendM = GET_MODE(msg->command);
        if(sendM == 32) {
		if(subislist[str]==0)  { //subWindows is not exist
			sub = new SubWindow(service,str);
			connect(sub , SIGNAL(delSub(QString)) , this, SLOT(delSub(QString)));
			sub->show();
			subislist[str]=1;
		}
	}
	//检查列表中是否已经有该用户
	foreach(QString s, sublist)
		if(!s.compare(str))
			return ;
	qDebug()<<"sublist.insert(usercount, str):"<<usercount<<"++"<<str;
	sublist.insert(usercount, str);
	subislist.insert(str, 0);
	qDebug()<<"subislist[str2]:" << subislist[str];
	usercount++;
        addUserphoto(NULL);
	showuserlist();
}

//加上用户头像（默认头像）
void MainWindow::addUserphoto(MessagePRO *msg)
{
        foreach(QString str, sublist)
        {
                qDebug()<<"User:"<<str;
                if (str.endsWith("*"))
                        userphoto[str]="./image/default.png";
                else
                        userphoto[str]="./image/ipmsg.png";
        }
}

//更新用户自定义头像
void MainWindow::chgUserphoto(MessagePRO *msg)
{
        QString str;
        if (msg->hostname == msg->username+"*")
                str=msg->address.toString()+":"+msg->username+"*";
        else
                str=msg->address.toString()+":"+msg->username;
        userphoto[str] = "./image/" + msg->extend;
        qDebug()<<userphoto[str];
        qDebug()<<str;
        showuserlist();
}

//把用户从列表删除
void MainWindow::delUserList(MessagePRO *msg)
{
	QString str=msg->address.toString()+":"+msg->username;
	int i=0;
	foreach(QString s, sublist)
	{	
		qDebug()<<"i:"<<i;
		if(!s.compare(str))
		{
			sublist.remove(i);
			usercount--;
			qDebug()<<"sublist.remove(i):"<<str<<"++"<<i;
		}
		i++;
	}
	showuserlist();
	qDebug()<<"delUserList()---------------";
}

//打开聊天子窗口
void MainWindow::addSub(QListWidgetItem *u)
{
        qDebug()<<"u->text:"<<u->text();
        QString str=u->text();
        qDebug()<<"str:"<<str;
        if(subislist[str]!=1)
        {
                sub = new SubWindow(service, u->text());
                connect(sub , SIGNAL(delSub(QString)) , this, SLOT(delSub(QString)));
                sub->show();
                subislist[str]=1;
        }
}

//关闭聊天子窗口
void MainWindow::delSub(QString str)
{

        qDebug()<<"MainWindow::delSub(QString str)";
        subislist[str]=0;

}

void MainWindow::closeEvent(QCloseEvent *event)
{
	qDebug()<<"closeEvent()------------------------------------";
	MessagePRO *msg = new MessagePRO;
        msg->command = IPMSG_BR_EXIT;
        msg->extend="";
	service->broadcast(6291458, NULL);
	service->udpSocket->close();
	event->accept();
}

//“关于”信息 
void MainWindow::about()
{
	QMessageBox::information(this, tr("About"),tr("This project is on Linux+QT4 platform, which was used for transfer files on Internet, providing communication with IP MSG, FeiQ or other clients. \nBY GXC in DT&P Version 1.0"));
}

//刷新用户列表
void MainWindow::refurbish()
{	
	service->broadcast(6291457, NULL);
	int i=0;
 	foreach(QString s, sublist)
        {
		sublist.remove(i);
		usercount--;
                i++;
        }
        qDebug()<<sublist<<"in MainWindow::refurbish";

	showuserlist();
}

//发送按钮的状态
void MainWindow::enabledSendButton()
{
	sendButton->setEnabled(true);
}

void MainWindow::getHostInformation()
{
        QString localHostName=QHostInfo::localHostName();
        //localHostName = QString::fromUtf8(localHostName.to);
        HostNameLabel->setText(localHostName);
        HostNameLabel->setAlignment(Qt::AlignCenter);
        //QHostInfo hostInfo = QHostInfo::fromName(localHostName);
	
}

void MainWindow::slotOpenImageDlg()
{
	qDebug()<<"SlotOpenImageDlg()------------------------------------";
	QString s = QFileDialog::getOpenFileName(this,"choose one image","./image","photo file(*.png);;jpg file(*.jpg)");
	if (s == NULL) {
            return;
	}
        else if (s != userPhoto) {
            userPhoto = s;
            photochange();
        }
        QPixmap icon(s);
        qDebug()<< s;
        ImageButton->setIcon(icon);
	//ImageButton->setIconSize(40,40);
        ImageButton->setIconSize(icon.size());
	ImageButton->update();
}

void MainWindow::photochange()
{
    qDebug()<<"photochange() in MainWindow::photochange()";
    qDebug()<<userPhoto;
    service->localuserphoto = userPhoto;
    QString theimageName = userPhoto.right(userPhoto.size() - userPhoto.lastIndexOf('/')-1);
    service->broadcast(9,theimageName);

}

